// DispatchServer.js

function DispatchServer() {
  const net = require("net");
  const port = 8000;
  const hostname = "127.0.0.1";
  let clients = [];
  let clientNo = 0;
  const server = new net.createServer();
  server.on("connection", (client) => {
    client.no = clientNo++;
    clients.push(client);
    client.on("data", function (msg) {
      console.log(`client ${client.no} data：${msg}`);
    });
    client.on("error", function (e) {
      console.log("client error" + e);
      client.end();
    });
    client.on("close", function () {
      delete clients[client.no];
      console.log(`${client.no} closed`);
    });
  });

  server.listen(port, hostname, function () {
    console.log(`listen http://${hostname}:${port}`);
  });

  const http = require("http");
  const webServer = http.createServer((req, res) => {
    if (req.url.startsWith("/post")) {
      if (clients.length > 0) {
        clients[Math.floor(Math.random() * clients.length)].write(
          req.url.substr(6)
        );
      }
      res.end("");
    } else {
      switch (req.url) {
        case "/clients":
          res.writeHead(200);
          res.end(JSON.stringify(clients));
          break;
        case "/post":
          if (clients.length > 0) {
            clients[Math.floor(Math.random() * clients.length)].write(
              req.url.substr(4)
            );
          }
          res.end("");
          break;
        default:
          res.writeHead(200);
          res.end("");
          break;
      }
    }
  });
  webServer.listen(8080);
}
module.exports = DispatchServer;
